<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\OrderTemporary;
use app\common\model\Pintuan as Pt ;
use app\common\tool\Result;
use think\Response;

class Pintuan extends Base
{
    public function submit(): Response
    {
        $param = $this->request->post();
        $res = Pt::submit($param, $this->user);
        if ($res['code'] === -1) {
            return Result::fail($res['msg']);
        }

        return Result::success('拼团已生成');
    }

    public function myQianggou(): Response
    {
        $param = $this->request->get();
        $map['uid'] = $this->user->id;
        if (!empty($param['status'])) {
            $map['status'] = $param['status'];
        }

        if (!empty($param['pid'])) {
            $map['pid'] = $param['pid'];
        }
        if (!empty($param['pintuan_date'])) {
            $map['pintuan_date'] = $param['pintuan_date'];
        }

        return Result::fastReturn(Pt::getPageList($map, 'id,title,icon,pid,parent_id,pintuan_pid,status,pintuan_date,create_time',
            $this->getPage(), $this->getLimit(), false, [], [], [], [], [], '', []));
    }

    public function getQianggou(): Response
    {
        $param = $this->request->get();

        $map['pintuan_date'] = date('Y-m-d');
        $map['pintuan_pid'] = 0;
        if (!empty($param['pid'])) {
            $map['pid'] = $param['pid'];
        }

        return Result::fastReturn(Pt::getPageList($map, 'id,title,icon,pid,parent_id,pintuan_pid,status,pintuan_date,create_time',
            $this->getPage(), $this->getLimit(), false, [], [], [], [], [], '', []));
    }

    public function subOrder(): Response
    {
        $param = $this->request->post();
        $param['type'] = 1;
        $param['num'] = 1;
        $pintuan_id = $param['pintuan_id'];
        $pintuaninfo = Pt::where(['id'=>$pintuan_id,'uid'=>$this->user->id,'status'=>2])->find();
        if(empty($pintuaninfo)){
            return Result::fail('拼团信息不匹配');
        }
        if(!empty($pintuaninfo->order_id)){
            return Result::fail('该拼团已参与抢购，请直接提交订单');
        }
        $date = date('Y-m-d');
        if($pintuaninfo->pintuan_date != $date ){
            return Result::fail('拼团成功订单只允许在当天参与购买');
        }
        $param['pid'] = $pintuaninfo['pid'];
        return Result::fastReturn(OrderTemporary::setTemporary($param, $this->user));
    }




}